package cashpointer.mobile;

import java.util.LinkedList;
import java.util.List;

import android.app.Dialog;
import android.app.ListActivity;
import android.content.ContentUris;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import cashpointer.mobile.dao.DAOFunctions;
import cashpointer.mobile.dao.DaoModel.Cashpoints;
import cashpointer.mobile.dao.DaoModel.Countries;
import cashpointer.mobile.dao.DaoModel.Owners;
import cashpointer.mobile.support.NotificationSupportManager;
import cashpointer.mobile.support.PreferencesManager;

public class FindedCashpointsFromLocationActivity extends ListActivity {

	/**
	 * Opcje menu.
	 */
	static private final int MENU_QUIT = Menu.FIRST;
	static private final int SHOW_ALL = Menu.FIRST + 1;

	/**
	 * Opcje dialog.
	 */
	static private final int DIALOG_LOCATION_IS_APPROXIMATE = 1001;
	
	//private static String LOG_TAG = "FindedCashpointsFromLocationActivity";
	
	private static final String[] COUNTRY_PROJECTION = new String[] {
    	Countries._ID, // 0
    };

	private static final String[] OWNER_PROJECTION = new String[] {
    	Owners._ID, // 0
    	Owners.NAME, // 1
    };
	
	private static final String[] CASHPOINT_PROJECTION = new String[] {
		Cashpoints._ID,
		Cashpoints.ADDRESS_CITY, 
		Cashpoints.ADDRESS_STREET, 
		Cashpoints.OWNER_ID, 
		Cashpoints.ADDRESS_LATITUDE, 
		Cashpoints.ADDRESS_LONGITUDE
    };
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		// Pobieram wartosc boolowska czy lokalizacja jest przyblizona
        Intent intent = getIntent();
        boolean isLocationApproximate = intent.getBooleanExtra(PreferencesManager.IS_LOCATION_APPROXIMATE, false);
        if (isLocationApproximate) {
			// Komunikat
    		showDialog(DIALOG_LOCATION_IS_APPROXIMATE);
        }
        
		// Pobieram dane potrzebne do zbudowania warunku WHERE
		String gpsRegion = PreferencesManager.getString(getApplicationContext(), PreferencesManager.FIND_GPS_REGION, "");
		String gpsCountry = PreferencesManager.getString(getApplicationContext(), PreferencesManager.FIND_GPS_COUNTRY, "");
		float latitude = PreferencesManager.getFloat(getApplicationContext(), PreferencesManager.FIND_GPS_LATITUDE, (float)0.0);
		float longitude = PreferencesManager.getFloat(getApplicationContext(), PreferencesManager.FIND_GPS_LONGITUDE, (float)0.0);
		
		// Budowanie warunku WHERE
		StringBuilder sb = new StringBuilder();
		String where =  null;
		sb.append(" 1 = 1 ");
		
		// Wybrani wlasciciele
		// Tworze kursor
		String ownerWhere = Owners.SELECTED + " = 1";
		Cursor ownerCursor = managedQuery(Owners.CONTENT_URI, OWNER_PROJECTION, ownerWhere, null, Owners.DEFAULT_SORT_ORDER);			

		// Bedzie przechowywal warunki OR dla wlascicieli
		StringBuilder ownerSb = new StringBuilder();
		
		// Przegladanie kursora
		if (ownerCursor.moveToFirst()) {
	        int idColumn = ownerCursor.getColumnIndex(Cashpoints._ID);
	        
	        do {
	        	// Pole "_ID"
				int cursorId = ownerCursor.getInt(idColumn);

				// Dodaje wyszukane ID
				ownerSb.append(" OR " + Cashpoints.OWNER_ID + " = " + cursorId);
	        } while (ownerCursor.moveToNext());
	    }
		
		// Zamykam kursor
		if (ownerCursor != null) {
			ownerCursor.close();
		}
		
		// Zawsze to dodaje poniewaz zawsze musi byc wybrany choc jeden wlasciciel
		sb.append(" AND (1 = 0 " + ownerSb.toString() + ") "); // 1 = 0 zawsze fausz, ale spelnia zadanie przy OR

		// Ustalam identyfikator wojewodztwa
		int gpsRegionId = DAOFunctions.getRegionReadOlny(getApplicationContext(), gpsRegion);
		
		// Ustalam identyfikator powiatu
		int gpsCountryId = DAOFunctions.getCountryReadOnly(getApplicationContext(), gpsCountry, gpsRegionId);
		
		// Wybrane wojewodztwo i powiat
		if (gpsRegionId > 0 && gpsCountryId > 0) { // konkretny powiat w wojewodztwie
			sb.append(" AND " + Cashpoints.COUNTRY_ID + " = " + gpsCountryId);
		} else if (gpsRegionId > 0) { // wszystkie powiaty z danego wojewodztw
			// Tworze kursor
			String regionWhere = Countries.REGION_ID + "=" + gpsRegionId;
			Cursor countryCursor = managedQuery(Countries.CONTENT_URI, COUNTRY_PROJECTION, regionWhere, null, Countries.DEFAULT_SORT_ORDER);			

			// Bedzie przechowywal warunki OR dla powiatow
			StringBuilder countrySb = new StringBuilder();
			
			// Przegladanie kursora
			if (countryCursor.moveToFirst()) {
		        int idColumn = countryCursor.getColumnIndex(Cashpoints._ID);
		        
		        do {
		        	// Pole "_ID"
					int cursorId = countryCursor.getInt(idColumn);

					// Dodaje wyszukane ID
					countrySb.append(" OR " + Cashpoints.COUNTRY_ID + " = " + cursorId);
		        } while (countryCursor.moveToNext());
		    }
			
			// Zamykam kursor
			if (countryCursor != null) {
				countryCursor.close();
			}
			
			if (countrySb.length() > 0) {
				sb.append(" AND (1 = 0 " + countrySb.toString() + ") "); // 1 = 0 zawsze fausz, ale spelnia zadanie przy OR
			}
		} else { // brak wojewodztwa
			// wszyskie bankomaty
		}

		// Tablica wspomagajaca wyslanie danych o polozeniu
		String[] location = new String[2];
		location[0] = String.valueOf(latitude);
		location[1] = String.valueOf(longitude);
		
		// Generowanie stringu z warunkiem where
		where = sb.toString();
		//Log.i(LOG_TAG, where);
		
		// Podpiecie layout'u
		setContentView(R.layout.finded_cashpoints_from_location);
		
		// Zbudowanie cursora i do pobrania danych
		Cursor cursor = managedQuery(Cashpoints.CONTENT_URI_TOP_10, null, where, location, null);
		
		// Utworzenie adaptera i pobranie danych z kursora
		startManagingCursor(cursor);
        
		String[] from = new String[] { Cashpoints.ADDRESS_CITY, Cashpoints.ADDRESS_STREET };
        int[] to = new int[] { R.id.text1, R.id.text2 };
        
        SimpleCursorAdapter notes = new SimpleCursorAdapter(this, R.layout.finded_cashpoints_row, cursor, from, to);
        setListAdapter(notes);
		
        // Przy obecnym wygladzie wyszukiwanie itak nie dziala ;)
        getListView().setTextFilterEnabled(false);
	}

	/**
     * Funkcja budowania menu.
     */
    public boolean onCreateOptionsMenu(Menu menu) {
    	menu.add(0, MENU_QUIT, 0, getString(R.string.menu_exit)).setIcon(R.drawable.menu_close);
    	menu.add(0, SHOW_ALL, 0, getString(R.string.menu_show_all)).setIcon(R.drawable.menu_map);
    	return true;
    }

    /**
     * Obsluga zdarzenia wybrania opcji z menu.
     */
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        	case MENU_QUIT: {
        		quit();
        		return true;
        	}
        	case SHOW_ALL: {
        		showAll();
        		return true;
        	}
        }
	    
        return false;
    }
    
    /**
     * Tworzy okno dialogu.
     */
    protected Dialog onCreateDialog(int id) {
        Dialog dialog;
        switch(id) {
	        case DIALOG_LOCATION_IS_APPROXIMATE: {
	        	dialog = NotificationSupportManager.buildInfoDialog(this, getString(R.string.notification_location_is_approximate));
	        	break;
		    }
	        default: {
	            dialog = null;
	        }
        }
        
        return dialog;
    }

	/**
     * Obsluga zdarzenia wybrania pozycji z listy
     */
    protected void onListItemClick(ListView l, View view, int position, long id) {
        super.onListItemClick(l, view, position, id);
        Intent intent = new Intent(this, CashpointActivity.class);
        intent.putExtra(PreferencesManager.CASHPOINT_SELECTED_ID, id);
		startActivity(intent);
    }

    /**
     * Funkcja konczenia aplikacji.
     */
    private void quit() {
    	this.finish();
    }
    
    /**
     * Funkcja pokazujaca wszystkie wyszukane bankomaty na mapie.
     */
    private void showAll() {
    	List<String> cityStreetList = new LinkedList<String>();
    	List<String> ownerList = new LinkedList<String>();
    	List<Double> latitudeList = new LinkedList<Double>();
    	List<Double> longitudeList = new LinkedList<Double>();
    	
    	ListAdapter listAdapter = this.getListAdapter();
    	for (int i = 0; i < listAdapter.getCount(); i++) {
    		// Identyfikator bankomatu
    		long id = listAdapter.getItemId(i);
    		
    		// Adres do wybranego rekordu z bazy (o danym id)
            Uri uriOfSelectedCashpoint = ContentUris.withAppendedId(Cashpoints.CONTENT_URI, id);
    		
            // Tworze kursor
            Cursor cashpointCursor = managedQuery(uriOfSelectedCashpoint, CASHPOINT_PROJECTION, null, null, Cashpoints.DEFAULT_SORT_ORDER);			

            // Przegladanie kursora
    		if (cashpointCursor != null && cashpointCursor.moveToFirst()) {
    	        int addressCityColumn = cashpointCursor.getColumnIndex(Cashpoints.ADDRESS_CITY);
    	        int addressStreetColumn = cashpointCursor.getColumnIndex(Cashpoints.ADDRESS_STREET);
    	        int ownerColumn = cashpointCursor.getColumnIndex(Cashpoints.OWNER_ID);
    	        int latitudeColumn = cashpointCursor.getColumnIndex(Cashpoints.ADDRESS_LATITUDE);
    	        int longitudeColumn = cashpointCursor.getColumnIndex(Cashpoints.ADDRESS_LONGITUDE);
    	        
    	        // Pole "CITY"
    			String cityStreet = cashpointCursor.getString(addressCityColumn);
    			
    	        // Pole "STREET"
    			String street = cashpointCursor.getString(addressStreetColumn);
    			cityStreet = cityStreet + " ul. " + street;
    			
    			cityStreetList.add(cityStreet);
    			
    			// Pole "OWNER"
    			int ownerId = cashpointCursor.getInt(ownerColumn);
    			Uri ownerUri = ContentUris.withAppendedId(Owners.CONTENT_URI, ownerId);
    			
    			// Tworze kursor dla Owner
    			String owner = "";
    	        Cursor ownerCursor = managedQuery(ownerUri, OWNER_PROJECTION, null, null, Owners.DEFAULT_SORT_ORDER);			
    			if (ownerCursor != null && ownerCursor.moveToFirst()) {
    				int nameColumn = ownerCursor.getColumnIndex(Owners.NAME);
    				owner = ownerCursor.getString(nameColumn);
    			}
    			ownerList.add(owner);
    			
    			// Zamykam kursor dla Owner
    			if (ownerCursor != null) {
    				ownerCursor.close();
    			}
    			
    			// Pole "latitude"
    			Double latitude = new Double(cashpointCursor.getDouble(latitudeColumn));
    			latitudeList.add(latitude);

    			// Pole "longitude"
    			Double longitude = new Double(cashpointCursor.getDouble(longitudeColumn));
    			longitudeList.add(longitude);
    	    } else {
    	    	//Log.w(LOG_TAG, "Brak bankomatu o id: " + id);
    	    }
    		
    		// Zamykam kursor
    		if (cashpointCursor != null) {
    			cashpointCursor.close();
    		}
    	}
    	
      	Intent intent = new Intent(this, CashpointMapActivity.class);
      	
      	double[] latitudeArray = new double[latitudeList.size()];
      	for (int i = 0; i < latitudeList.size(); i++) {
    		latitudeArray[i] = (double)latitudeList.get(i);
    	}
    	intent.putExtra(PreferencesManager.CASHPOINT_SELECTED_LATITUDE, latitudeArray);
    	
    	double[] longitudeArray = new double[longitudeList.size()];
    	for (int i = 0; i < longitudeList.size(); i++) {
    		longitudeArray[i] = (double)longitudeList.get(i);
    	}
    	intent.putExtra(PreferencesManager.CASHPOINT_SELECTED_LONGITUDE, longitudeArray);
    	
    	String[] cityStreetArray = new String[cityStreetList.size()];
    	for (int i = 0; i < cityStreetList.size(); i++) {
    		cityStreetArray[i] = new String(cityStreetList.get(i));
    	}
    	intent.putExtra(PreferencesManager.CASHPOINT_SELECTED_CITY_STREET, cityStreetArray);
    	
    	String[] ownerArray = new String[ownerList.size()];
    	for (int i = 0; i < ownerList.size(); i++) {
    		ownerArray[i] = new String(ownerList.get(i));
    	}
    	intent.putExtra(PreferencesManager.CASHPOINT_SELECTED_OWNER, ownerArray);
    	
    	startActivity(intent);
	}
}
